package com.it.filter;

import cn.hutool.core.util.StrUtil;
import com.it.exception.GeneralException;
import com.it.util.JwtUtil;
import com.it.util.ResultCodeEnum;
import com.it.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OncePerRequestFilter 每一请求的过滤器
 * 令牌身份验证过滤器
 *
 * @author 16272
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    // 全局异常通知对象
    @Resource
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver handlerException;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 如果是登录请求直接放行
        if (isLoginRequest(httpServletRequest)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        // 非登录请求需要校验token
        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
            String username = JwtUtil.getUsername(token);
            Long userId = JwtUtil.getUserId(token);
            if (username != null && userId != null) {
                ThreadLocalUtil.setUserId(userId);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
        }

        handlerException.resolveException(httpServletRequest, httpServletResponse, null, new GeneralException(ResultCodeEnum.LOGIN_AUTH.getMessage(), ResultCodeEnum.LOGIN_AUTH.getCode()));
    }

    private boolean isLoginRequest(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        return "/user/login".equals(requestURI) || "/user/register".equals(requestURI)||request.getMethod().equals("OPTIONS");
    }
}
